import React, { useRef, useState, useEffect } from 'react';
import { View, Image, Text, ScrollView,Textarea,Swiper,SwiperItem } from '@tarojs/components';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import {AtIcon , AtModal,AtActionSheet} from 'taro-ui'
import OrderCancleReason from '../activityCancleReason/index';
import QRCode from '@/utils/weapp-qrcode.js'
import { commentUploadImgServer } from '@/services/comment';
import './index.less';

import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/modal.scss";
import "taro-ui/dist/style/components/action-sheet.scss";

const MovieDetail = ({ }) => {
  const limitCount = 9
  const [info,setInfo] = useState({})
  const id = useRef('')
  const OrderStatus = ['待支付','购票成功，活动即将开始','交易取消','活动已结束','已退款','购票成功，活动正在进行']
  const [curData,setCurData] = useState({})
  const [showModal,setShowModal] = useState(false)
  const [codeImg,setCodeImg] = useState([])
  const [curSwiper,setCurSwiper] = useState(0)
  const [showPrice,setShowPrice] = useState(false)
  const [showExpire,setShowExpire] = useState(false)
  const [showInfo,setShowInfo] = useState(false)
  const [showAfter,setShowAfter] = useState(false)
  const [showUpload,setShowUpload] = useState(false)
  const [uploadMap, setUploadMap] = useState({});
  const [config,setConfig] = useState({})
  const [PopupService, setPopupService] = useState(false)

  useEffect(()=>{
    id.current = getCurrentInstance().router.params.orderId
    _initData(getCurrentInstance().router.params.orderId)
    Taro.setNavigationBarColor({
      backgroundColor:'#ed3c54',
      frontColor:'#ffffff'
    })
  },[])
  const [isOpened, setIsOpened] = useState(false);
  const handleSelected = (reasonStatus,data) => {
    setUploadMap({...uploadMap,
      reason:reasonStatus,
      reasonName:data.value
    })
    setIsOpened(false);
  };

  const [state, updateState] = useState({
    files: [],
  });
  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };
  //选择图片
  const handleChooseImage = () => {
    Taro.chooseImage({
      count: 9 - state.files.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if (state.files.length + res.tempFilePaths.length > limitCount) {
          Taro.showToast({
            title: `最多上传${limitCount}张图片`,
            duration: 1000,
            icon: 'none',
          });
        } else {
          setState({ files: state.files.concat(res.tempFilePaths) });
        }
      },
    });
  };
  //删除图片
  const handleDelImg = (idx) => {
    //因渲染机制增加定时器
    setTimeout(() => {
      state.files.splice(idx, 1);
      setState({
        files: state.files,
      });
    }, 0);
  };
  const handleSubmit = e=>{ /// 提交数据
    const data = {
      "cerImageUrl": uploadMap?.files,
      "description": uploadMap?.description,
      "orderId": info.orderId,
      "reason": uploadMap?.reason
    }
    if(!data.reason){
      Taro.showToast({
        title:'请先选择退款原因',
        icon:'none'
      })
      return;
    }
    Taro.$post(`/order/after-sales/commit`,data).then(res=>{
      if(res.code == '1'){
        Taro.showToast({
          title:'提交成功',
          icon:'success'
        })
        setShowAfter(false)
        setTimeout(() => {
          _initData(data.orderId)
        }, 1000);
      }else{
        Taro.showToast({
          title:res.message,
          icon:'none'
        })
      }
    })
  }
  const updateTimeData = e=>{
    const timeData = {}
    const time = info.processingTime*1000 || 0
    if(time){
      timeData.day = Math.floor(time / 1000 / 60 / 60 / 24);
      timeData.hour = Math.floor((time / 1000 / 60 / 60) % 24);
      timeData.minute = Math.floor((time / 1000 / 60) % 60);
      timeData.second = Math.floor((time / 1000) % 60);
    }
    return timeData
  }
  const _initData =e=>{
    Taro.showLoading({title:'加载中...'})
    Taro.$get(`/act/orders/v3/${e || getCurrentInstance().router.params.orderId}`,'','1').then(res=>{
      if(res.code == '1'){
        setInfo(res.content)
        if(res.content.ticketCodeList?.length){
          let arr = []
          res.content.ticketCodeList.map(async ret=>{
            arr.push(QRCode.drawImg(ret.ticketCode, {
              size: 320
            }))
          })
          setCodeImg(arr)
        }else{
          setCodeImg([])
        }
      }
    })
  }
  return (
  <View className="movie-detail">
    <View className='detail-status'>
      <Text className='at-icon at-icon-check-circle' style={{marginRight:'6px',fontSize:'20px'}}></Text> {info.businessStatusDesc}
      {info.businessStatusDesc?.includes('退款')?<>
        <View className="status-span">{info.processingTimeDesc}</View>
        <View className="status-price"><Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}</View>
        <View className="status-p">
          {info.afterSaleTime} <br /> {info.businessStatus == '3' || info.businessStatus == '5'?'商家已退款，钱款已原路退回。':'商家已收到您的退款申请，正在等待商家审核。'}
        </View>
      </>:null}
    </View>
    <View className="detail-header">
      <View className="header-address">
        <View className="omit" style={{width:'85%'}}>{info.location?.name}</View>
        <Image onClick={()=>{
          Taro.openLocation({
            latitude: parseFloat(info.location.latitude),
            longitude: parseFloat(info.location.longitude),
            scale: 18,
            name:info.location.name,
            address:info.location.address,
          });
        }} style={{width:'20px',height:'20px'}} mode='aspectFill' src={require('@/static/icon_map-pin.png')} />
      </View>
      <View style={{display:'flex',flexWrap:'wrap'}}>
        <Image className="header-img" src={info.media} />
        <View className="header-info">
          <View className="omit h2">{info.topicTitle}</View>
          <View className='p' style={{color:'#66686A'}}>
            <View className="p-left">{info.dateStr}</View>
            {info.hallName}
          </View>
          <View className='p'>
            <View className="p-left">{info.timeStr}</View>
            <View className="box-flex">
              {info.seats?.map(res=>{
                return <Text key={res} style={{marginRight:'10px'}}>{res}</Text>
              })}
            </View>
          </View>
        </View>
      </View>
    </View>
    {codeImg.length?
    <View className="detail-ticket">
      <View className="ticket-title"><Text className='line'></Text><Text className='theme-color'>{curSwiper+1}</Text>/{codeImg.length} 张<Text className='line'></Text></View>
      <View className="ticket-subTitle">凭下方「电子检票码」检票入场</View>
      <Swiper className="ticket-list" circular indicatorDots={false} current={curSwiper} onChange={e=>{
        setCurSwiper(e.detail.current)
      }}>
        {codeImg.map(item=>(
          <SwiperItem className="list-item" key={item}>
            <Image className='item-img' src={item} />
            {info.isOwnChannel?<>
              <View className="item-h3">{info.ticketCodeList[curSwiper].seatName}</View>
              <View className="item-p">{(info.totalPayment*1)/info.ticketCodeList.length}元</View>
            </>:null}
            <View className="item-code">
              检票码 <Text style={{color:'#26282A'}}>{info.ticketCodeList[curSwiper]?.ticketCode}</Text>
            </View>
          </SwiperItem>
        ))}
      </Swiper>
      {info.isOwnChannel?
      <View className="swiper-dots">
        <Image src={require('@/images/dots-left.svg')} className='dot-left' onClick={()=>{
          setCurSwiper(curSwiper - 1 < 0 ? codeImg.length-1 : curSwiper - 1)
        }}></Image>
        <Image src={require('@/images/dots-right.svg')} className='dot-right' onClick={()=>{
          setCurSwiper(curSwiper + 1 > codeImg.length-1 ? 0 : curSwiper+1)
        }}></Image>
      </View>:null}
    </View>:null}
    
    {info.canRefundOrder?
    <View className="detail-card">
      <View className="card-title">退票规则</View>
      <View className="card-retund">
        <View className="retund-info">
          <Text className="info-tag">条件退票</Text>
          <View style={{marginTop:8}}>该活动支持退票，退票需要收取手续费，具体规则如下：</View>
        </View>
        <View className="retund-button" onClick={()=>{
          Taro.$get(`/order/users/orders/checkAfterSale`,{orderId:getCurrentInstance().router.params.orderId}).then(res=>{
            if(res.code == '1'){
              setShowAfter(true)
            }else{
              setShowExpire(true)
            }
          })
        }}>退票</View>
      </View>
      <View className="item-table">
        <View className="table-header table-main"><Text>申请退票时间段</Text><Text>退票手续费</Text></View>
        <View className="table-body table-main">
          {info.refundRule?.map((res,idx)=>{
            return <View key={res.timeSlot} className={`body-item ${info.refundRule.findIndex(ret=>ret.selected)>idx?'gary':''}`}><Text>{res.timeSlot}{res.selected?<Text className='item-cur'>当前阶段</Text>:null}</Text><Text>{res.refundServiceCharge}</Text></View>
          })}
        </View>
      </View>
    </View>:null}
    <AtActionSheet isOpened={showExpire} onClose={()=>{setShowExpire(false)}}>
      <View className="expire-modal">
        <Image className='modal-img' src={require('@/static/Illustration.png')} />
        <View className="modal-h1">抱歉，订单已过售后申请时效</View>
        <View>如您对商品售后有疑问，可联系客服处理</View>
        <View className="modal-button" onClick={()=>{
          setShowExpire(false)
        }}>返回</View>
      </View>
    </AtActionSheet>
    <AtModal isOpened={showModal} onClose={()=>{setShowModal(false)}}>
      <View className="modal-main">
        <View className="main-header">
          <Image className="header-logo" src={info.media} />
          <View className="header-info">
            <View className="omit-2 h2">{info.activityName}</View>
            <View className="box-flex">
              <View>{info.startTime} {info.dateDesc} {info.timeRange}</View>
            </View>
          </View>
        </View>
        {curData.ticketCode?
        <View className="main-code">
          <Image src={codeImg} className='code-img' />
          <View className="p" style={{marginBottom:'5px'}}>{curData.ticketCode}</View>
          {info.hallName?<View className='p'>{info.hallName + ' ' + curData.seatName}</View>:<View className='p'>{curData.seatName}</View>}
        </View>:null}
      </View>
    </AtModal>
    {info.topicNotes?.length?<View className="detail-card" onClick={()=>{setPopupService(true)}}>
      <View className="card-title">观演须知</View>
      <View className="viewing-list">
        {info.topicNotes?.map(res=>{
          return <View className="list-item" key={res.title}>
          <View className="item-h2">{res.title}</View>
          <View className="item-p dot">{res.desc}</View>
        </View>
        })}
      </View>
    </View>:null}
    <AtActionSheet isOpened={PopupService} onClose={()=>{setPopupService(false)}}>
      <View className="popup-service">
        <View className="service-header">
          <View className='h2'>观演须知</View>
          <Image onClick={()=>{setPopupService(false)}} src={require('@/static/close.png')} className="header-close"></Image>
        </View>
        <View className="service-list">
          {info.topicNotes?.map(res=>{
            return <View className="list-item" key={res.title}>
              <View className='p'>{res.title}</View>
              {res.desc}
            </View>
          })}
        </View>
      </View>
    </AtActionSheet>
    <View className="detail-intro">
      <View className="intro-title">订单详情</View>
      <View className="intro-list"><View className='p'>实付金额</View> ¥{info.totalPayment}</View>
      <View className="intro-list"><View className='p'>订单编号</View> {info.orderId} <View className="item-copy" onClick={()=>{
          Taro.setClipboardData({
            data:info.orderId,
            success:res=>{
              Taro.$toast('复制成功','success')
            }
          })
        }}><Image src={require('@/images/common/copy.svg')} mode='widthFix'></Image> 复制</View></View>
        {info.paymentTime?
        <View className="intro-list">
          <View className='p'>付款时间</View>
          {info.paymentTime}
        </View>:null}
        <View className="intro-list"><View className='p'>支付方式</View> {info.payMethod || '微信支付'}</View>
    </View>

    <OrderCancleReason
      isOpened={isOpened}
      handleClose={()=>{setIsOpened(false)}}
      handleSelected={handleSelected}
      key={id.current}
      source={info.orderSource}
    />
    <AtActionSheet isOpened={showAfter} onClose={()=>{setShowAfter(false)}}>
      <View className="activity-popup">
        <View className="popup-header">
          <View></View><View className="header-h2">确认退款信息</View>
          <AtIcon value='close' size='16' color='#000' onClick={()=>{setShowAfter(false)}}></AtIcon>
        </View>
        <View className="popup-main">
          <View className="main-item">
            <Image className="main-img" src={info.media} />
            <View className="main-info">
              <View className="omit h2">{info.topicTitle}</View>
              <View className='p' style={{color:'#66686A'}}>
                <View className="p-left">{info.dateStr}</View>
                {info.hallName}
              </View>
              <View className='p'>
                <View className="p-left">{info.timeStr}</View>
                <View className="box-flex">
                  {info.seats?.map(res=>{
                    return <Text key={res} style={{marginRight:'10px'}}>{res}</Text>
                  })}
                </View>
              </View>
            </View>
          </View>
          <View className="main-list">
            <View className="list-p">退款原因</View>
            <Text style={{color:'#90989F'}} onClick={()=>{setIsOpened(true)}}>{uploadMap?.reasonName || '请选择退款原因'} <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon></Text>
          </View>
          <View className="main-list">
            <View className="list-p">退款金额</View>
            <Text>￥</Text>{info.totalPayment}
          </View>
          <View className="main-list">
            <View className="list-p">上传描述和凭证</View>
            {uploadMap?.files?.length || uploadMap?.description?<><Text onClick={()=>{setShowUpload(true)}}>
              {uploadMap?.files?.length?' 凭证':null}
              {uploadMap?.description?' 描述':null} 
              <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon>
            </Text></>:
            <><Text style={{color:'#90989F'}} onClick={()=>{setShowUpload(true)}}>上传有助于处理问题 <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon></Text></>}
          </View>
        </View>
        <View className="popup-footer">
          <View className="footer-info"><Text style={{fontWeight:'500',color:'#30383F',marginRight:'8px'}}>退款总金额</Text> <Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}</View>
          <View className="footer-button" onClick={()=>{handleSubmit()}}>提交申请</View>
        </View>
      </View>
    </AtActionSheet>
    <AtActionSheet isOpened={showUpload} onClose={()=>{setShowUpload(false)}}>
      <View className="activity-popup">
        <View className="popup-header">
          <View></View><View className="header-h2">上传描述和凭证</View>
          <AtIcon value='close' size='16' color='#000' onClick={()=>{setShowUpload(false)}}></AtIcon>
        </View>
        <View className="popup-main">
          {showUpload?
          <Textarea style={{height:'100px',width:'100%'}} maxlength={200} placeholder='补充描述,有助于商家更好的处理售后问题' onInput={e=>{
            setState({...state,description:e.detail.value})
          }}></Textarea>:null}
          <View className="main-imgs">
            {state.files.length < 9?
            <><View className="imgs-button imgs-item" onClick={()=>{handleChooseImage()}}>
              上传凭证<br />(最多9张)
            </View></>:null}
            {state.files.map((box,idx)=>(
              <View className="imgs-item" key={idx}>
                <Image src={box} mode='aspectFill' className='item-img' />
                <Image src={require('@/static/close.png')} onClick={()=>{handleDelImg(idx)}} className='item-icon' />
            </View>
            ))}
          </View>
        </View>
        <View className="popup-footer" style={{marginTop:'10px'}}>
          <View className="footer-button" style={{borderRadius:'40px'}} onClick={async ()=>{
            let imgs = {};
            let files = uploadMap.files || []
            const imgUrls = state.files || [];
            for (let file of imgUrls) {
              if (!!uploadMap[file]) {
                //避免重复上传
                imgs[file] = uploadMap[file];
                continue;
              }
              const fileRes = await commentUploadImgServer(file);
              if (fileRes.code == 1 && fileRes.content) {
                imgs[file] = fileRes.content;
                files.push(fileRes.content)
              }else{
                Taro.showToast({
                  title:'上传失败',
                  icon:'none'
                })
                return;
              }
            }
            setUploadMap(pre=>{
              return {
                ...pre,
                ...imgs,
                files,
                description:state.description
              }
            })
            setShowUpload(false)
          }}>完成</View>
        </View>
      </View>
    </AtActionSheet>
  </View>
  );
};

export default MovieDetail